package ru.spbsu.electromenu.storage.db;

import org.springframework.jdbc.core.RowMapper;
import ru.spbsu.electromenu.model.Table;
import ru.spbsu.electromenu.storage.TableStorage;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Date: 3/22/11
 * Time: 1:04 AM
 *
 * @author Artem Titov
 */
public class TableDbStorage extends AbstractDbStorage implements TableStorage {

    private final RowMapper<Table> TABLE_ROW_MAPPER = new RowMapper<Table>() {
        @Override
        public Table mapRow(ResultSet rs, int i) throws SQLException {
            final Table table = new Table();
            table.setId(rs.getInt("Id"));
            return table;
        }
    };

    @Override
    public Table get(int id) {
        return jdbcTemplate.queryForObject("select * from `Table`", TABLE_ROW_MAPPER);
    }

    @Override
    public int put(Table table) {
        return jdbcTemplate.update("insert into `Table` values (?)", table.getId());
    }

    @Override
    public int update(Table table) {
        return jdbcTemplate.update("update `Table` set `Id`=? where `Id`=?", table.getId(), table.getId());
    }

    @Override
    public int delete(int id) {
        return jdbcTemplate.update("delete from `Table` where `Id`=?", id);
    }

    @Override
    public List<Table> getALl() {
        return jdbcTemplate.query("select * from `Table`", TABLE_ROW_MAPPER);
    }
}
